package com.kawaiim.zhj.GameProcess;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;

import java.text.MessageFormat;
import java.util.Random;

import com.kawaiim.zhj.LandlordActivity;
import com.kawaiim.zhj.GameAnimation.DeckOperator;
import com.kawaiim.zhj.GameAnimation.PokeOperator;
import com.kawaiim.zhj.R;
import com.kawaiim.zhj.GameAnimation.CardAnimator;
import com.kawaiim.zhj.utilities.Constants;
import com.kawaiim.zhj.utilities.DensityUtil;

import cn.pedant.SweetAlert.SweetAlertDialog;

//一轮结束后结算积分
public class ScoreSettleProcess  {

    //获取当前进行的游戏
    private LandlordActivity game;

    //对扑克操作
    private DeckOperator deckOperator;
    //设置卡牌图片
    private PokeOperator stp;

    //最终得分
    private final int[] lastScore = new int[4];

    public ScoreSettleProcess(LandlordActivity game) {
        this.game = game;
        //初始化随机种子
        Random ran = new Random();

        stp = game.pokeOperator;
        deckOperator = game.deckOperator;
    }

    //获胜结算，显示结束计分板
    public void startSettleScore() {
        //计算最终计分
        countFourPeopleScore();

        //播放胜利或者失败的音效
        game.soundEffect.Player_EndGame_Voice(lastScore[0] > 0);


        //移除显示的四个图标
        for (int i = 0; i < 4; i++) {
            game.players[i].actionAlphaGoneRun();
        }

        //将其余三家剩余的牌翻转
            for (int i = 1; i < 4; i++) {
                //有剩余牌
                if (!game.players[i].cards.isEmpty()) {
                    showAnimator_OverTurnThreeBright(i, game.players[i].cards.size() - 1);
                }

        }
            //重新开始
            //start_new_turn_click();
            //game.set
        SweetAlertDialog dialog = new SweetAlertDialog(game, SweetAlertDialog.CUSTOM_IMAGE_TYPE)
                .setTitleText("本局游戏结束")
                .setContentText("加qq群（680458714）交流")
                .setConfirmText("继续下一局")
                .setCancelText("复制群号")
                .setCustomImage(lastScore[0] > 0 ? R.mipmap.win : R.mipmap.lose)

                .setConfirmClickListener(sDialog -> {
                    sDialog.cancel();
                    start_new_turn_click();

                })
                .setCancelClickListener(sDialog -> {

                    ClipboardManager clipboard = (ClipboardManager) game.getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clipData = ClipData.newPlainText(null, "680458714");
                    clipboard.setPrimaryClip(clipData);
                    Toast.makeText(game.getApplicationContext(), "已复制打开qq查找添加", Toast.LENGTH_SHORT).show();


                });
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();



    }

    //计算四个人最终得分，并将得分存放到lastScore数组里面
    private void countFourPeopleScore() {
        int[] OrignIntegration = new int[4];

        //保存上一局四人原本的积分
        for (int i = 0; i < 4; i++) {
            OrignIntegration[i] = game.players[i].integration;
        }

        //结算上一局最终的积分
        game.peopleOperator.settleScore(game.players, game.integration[0]);

        //将最终积分保存到lastScore中
        for (int i = 0; i < 4; i++) {
            lastScore[i] = game.players[i].integration - OrignIntegration[i];
        }
    }

    //结束积分“X”按钮的事件，删除结束的积分界面，初始化各种变量，显示开始按钮
    public void start_new_turn_click() {

        //对积分榜进行更新
        updateScorePanel();

        //显示开始按钮
        game.start_button.setVisibility(View.VISIBLE);
        //显示开始按钮
        CardAnimator.alphaRun(game.start_button, Constants.LIGHT_DURATION_TIME);


        //如果是单机状态，其他三家自动准备

            /*//初始化四个人的开始图片
            for (int i = 1; i < 4; i++) {
                //添加score图片（叫分和开始的图片）（淡入）
                game.players[i].setAction(PeopleActionEnum.PREAPARE);
            }*/

        //积分结算结束，进入状态转移
        game.process.gameProcessChange();
    }
    //更新积分榜
    public void updateScorePanel() {


            //更新当前总积分
            game.lbl_bottomscore.setText(MessageFormat.format("总积分：{0}", game.players[0].integration));

    }

    //将其余三家翻转变明
    //setElevation(i * 2 + game.poke[cardIndex].getElevation())是为了在翻转过程中能保持相对高度不变
    public void showAnimator_OverTurnThreeBright(final int who, final int i) {
        final float start = 0f;
        final float end1 = (180.0F) / Constants.beishu;
        final float end2 = 180.0F;
        if (i >= 0 && i < game.players[who].cards.size()) {
            final int num = game.players[who].cards.get(i).cardIndex;

            //设置翻转时间
            final int duration = (int)(Constants.UNDERPOKE_DURATION_TIME);
            CardAnimator.rotationYRun(game.poke[num], (long)(duration / Constants.beishu), start, end1);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //再从背面转换为正面
                    stp.setPokePicture(num, false);
                    game.poke[num].setElevation(i * 2 + game.poke[num].getElevation());
                }
            }, duration / 2 + Constants.WAIT_FOR_COUNT);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    CardAnimator.rotationYRun(game.poke[num], (long)(duration * (Constants.beishu - 1) / Constants.beishu), end1, end2);
                    if (i > 0) {
                        //从右至左
                        showAnimator_OverTurnThreeBright(who, i - 1);
                    } else {
                        //全部翻转完后，将阴影相同，刷牌
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < game.players[who].cards.size(); i++) {
                                    int num = game.players[who].cards.get(i).cardIndex;
                                    game.landlord_layout.removeView(game.poke[num]);
                                    game.landlord_layout.addView(game.poke[num]);
                                    game.poke[num].setElevation(DensityUtil.dip2px(game.getApplication(), Constants.ElEVATION_DP));
                                }
                            }
                        }, (long)(duration * (Constants.beishu - 1) / Constants.beishu));
                    }
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (i < game.players[who].cards.size()) {
                                stp.setPokePicture(game.players[who].cards.get(i).cardIndex, false);
                            }
                        }
                    }, (long)(duration * (Constants.beishu - 1) / Constants.beishu) + Constants.WAIT_FOR_COUNT);
                }
            }, (long)(duration / Constants.beishu));
        }
    }

    //将其余三家翻转变暗
    public void showAnimator_OverTurnThreeDark(final int who, final int i) {
        final float start;
        final float end1;
        final float end2;
        if (i >= 0 && i < game.players[who].cards.size()) {
            final int num = game.players[who].cards.get(i).cardIndex;
            start = 180.0F;
            end1 = start / Constants.beishu * (Constants.beishu - 1);
            end2 = 0f;
            final int duration = (int)(Constants.UNDERPOKE_DURATION_TIME);//设置翻转时间
            CardAnimator.rotationYRun(game.poke[num], (long)(duration / Constants.beishu), start, end1);
            if (i >= Constants.excursion_num + 1) {
                game.poke[num].setElevation((game.players[who].cards.size() - 3 - i) + 25 + DensityUtil.dip2px(game.getApplication(), Constants.ElEVATION_DP));
            }

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    stp.setPokePicture(num, true); //再从背面转换为正面
                    if (i < Constants.excursion_num + 1) {   //在0~17，18张牌的时候换行
                        game.poke[num].setElevation((game.players[who].cards.size() - 3 - i) + DensityUtil.dip2px(game.getApplication(), Constants.ElEVATION_DP));
                    }
                }
            },duration / 2 + Constants.WAIT_FOR_COUNT);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    CardAnimator.rotationYRun(game.poke[num], (long)(duration * (Constants.beishu - 1) / Constants.beishu), end1, end2);
                    if (i < game.players[who].cards.size() - 1) {
                        //从左至右
                        showAnimator_OverTurnThreeDark(who, i + 1);
                    }
                    else if (i == game.players[who].cards.size() - 1) {
                        //全部翻转完后，将阴影相同，刷牌
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                deckOperator.freshOthersDeck(who);
                            }
                        }, (long)(duration * (Constants.beishu - 1) / Constants.beishu));
                    }
                }
            }, (long) (duration / Constants.beishu));
        }
    }

}
